import {store,app} from '@/main';
import axios from 'axios';
import {isObject} from '../utils/index';
import apiConfig from '../api-config';
let param = function (obj) {
    var query = '', name, value;
    for(name in obj) {
        value = obj[name];
        if(value instanceof Array) {
            query += encodeURIComponent(name) + '=' + encodeURIComponent(JSON.stringify(value)) + '&';
        }
        else if(value instanceof Object) {
            query += encodeURIComponent(name) + '=' + encodeURIComponent(JSON.stringify(value)) + '&';
        }
        else if(value !== undefined && value !== null)
            query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
    }
    return query.length ? query.substr(0, query.length - 1) : query;
};
if(apiConfig.BUILD){
    axios.defaults.timeout =  5000;
}
axios.defaults.baseURL = apiConfig.url;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
/**
 *
 * @param data_noAuth属性：代表不处理90*异常
 * @param url
 * @param method
 * @returns {Promise.<TResult>|*}
 */
export default (data, url,method)=> {
    data = data||{};
    const _noAuth = data._noAuth||false;
    delete data._noAuth;
    const _noProgress = data._noProgress||false;
    delete data._noProgress;
    if(store&&store.getters&&store.getters.user){
        data['token'] = store.getters.user.token;
    }
    var obj = {
        url: url,
        method: method||'post',
        transformRequest: [function (data) {
            return isObject(data) && String(data) !== '[object File]' ? param(data) : data;
        }],
        transformResponse: [function (data) {
            return data;
        }],
        data:data,
        responseType: 'json',
        progress: function (progressEvent) {}
    };
    if(method=='get'){
        delete obj.data;
        obj.params = data;
    }
    if(!_noProgress){app.$nprogress.start();}
    return axios.request(obj).then(function (res) {
        if(!_noProgress){app.$nprogress.done();}

        if(!_noAuth&&res.data&&res.data.code&&res.data.code.toString().match(/90[12345]/)){
            if( res.data.code == 902 ||
                res.data.code == 903 ||
                res.data.code == 904){
                if(res.data.code == 904){
                    if(!!app.$route.matched[0][name]){
                        app.$router.back()
                    }else {
                        app.$router.push({name:'Home'});
                    }
                }else{
                    //app.$Message.warning('请登录');
                    res.data.message = '';
                    app.$router.push({name:'Login'});
                }
            }
        }
        return res.data
    },function (err) {
        if(!_noProgress){app.$nprogress.done();}
        if(err.toString()==('Error: timeout of '+axios.defaults.timeout+'ms exceeded')){
            app.$Notice.open({
                title:'网络请求超时',
                desc: '超时：控制台查看详情',
                duration:3
            });
            console.warn('网络请求超时,接口：'+url);
        }else {
            app.$Notice.open({
                title:'网络错误',
                desc: '错误：控制台查看详情',
                duration:3
            });
            console.warn('网络错误,接口：'+url+'。',err);
        }

    })
}